﻿using System;
using System.Web;
using System.Text.RegularExpressions;
using umbraco;
using UComment.Domain;
using umbraco.presentation.umbracobase;

namespace UComment.Library
{
    [RestExtension("UComment")]
    public class Base
    {
        [RestExtensionMethod(returnXml = false)]
        public static int CreateComment(int parentId)
        {
            var post = HttpContext.Current.Request;
            
            var email = post["email"];
            var commentText = post["comment"];
            var name = post["author"];
            var website = post["url"];
            
            //if all values are there + valid email.. we start to create the comment
            if (!string.IsNullOrEmpty(email) && IsValidEmail(email) && !string.IsNullOrEmpty(commentText) && !string.IsNullOrEmpty(name))
            {                                  
                var checker = Config.GetChecker();

                var isSpam = false;
                if (checker != null)
                {
                    isSpam = checker.Check(parentId,
                        post.UserAgent, post.UserHostAddress,
                        name, email, website, commentText);
                }

                Comment.MakeNew(parentId, name, email, website, isSpam, DateTime.Now, commentText);
                return 1;
            }
            
            //if nothing gets created, we return zero
            return 0;
        }

        [RestExtensionMethod(returnXml = false)]
        public static string GetGravatarImage(string email, int size)
        {
            return IsValidEmail(email) ? string.Format("http://www.gravatar.com/avatar/{0}?s={1}", library.md5(email), size) : "";
        }

        private static bool IsValidEmail(string email)
        {
            var r = new Regex(@"^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$");
            return !string.IsNullOrEmpty(email) && r.IsMatch(email);
        }

    }
}
